package mudus;

import com.mysql.jdbc.log.LogUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;

public class Message {

    public static byte[] createErrLoginMsg() {
        String s = "err:0";
        return s.getBytes();
    }
    
    public static byte[] createSuccessLoginMsg() {
        String s = "proceed";
        return s.getBytes();
    }
    
    public static byte[] createMetaFileMsg(File file) {        
        long filesize = file.length();
        int npiece = (int) Math.ceil(filesize * 1.0d / GlobalSettings.PIECE_LENGTH);
                
        StringBuilder sb = new StringBuilder();
        sb.append(file.getName()).append("|");
        sb.append(filesize).append("|");
        sb.append(GlobalSettings.PIECE_LENGTH).append("|");        
        sb.append(npiece).append("|");
        
        return sb.toString().getBytes();
    }
    
    public static byte[] createFilePieceMsg(int ipiece, byte[] data) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(ipiece);                       
        byte[] bipiece = bb.array();
                        
        byte[] ret = new byte[bipiece.length + data.length];
        
        System.arraycopy(bipiece, 0, ret, 0, bipiece.length);        
        System.arraycopy(data, 0, ret, bipiece.length,data.length);                                
        return ret;
    }
    
    public static byte[] createUploadGrantMsg() {
        String s = "granted";
        return s.getBytes();        
    }
    
    public static byte[] createACKPiece(int ipiece) {
        String s = "ACK " + ipiece;
        return s.getBytes();
    }
    
    public static byte[] createMetaLogFile(UserInfo userInfo) throws FileNotFoundException {
        File log = LogFile.getLogFile(userInfo);
        long filesize = log.length();
        int npiece = (int) Math.ceil(filesize * 1.0d / GlobalSettings.PIECE_LENGTH);
                
        StringBuilder sb = new StringBuilder();
        sb.append(log.getName()).append("|");
        sb.append(filesize).append("|");
        sb.append(GlobalSettings.PIECE_LENGTH).append("|");        
        sb.append(npiece).append("|");
        
        return sb.toString().getBytes();
    }
    
    public static byte[] createLogFilePiece(int ipiece, byte[] data) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(ipiece);                       
        byte[] bipiece = bb.array();
                        
        byte[] ret = new byte[bipiece.length + data.length];
        
        System.arraycopy(bipiece, 0, ret, 0, bipiece.length);        
        System.arraycopy(data, 0, ret, bipiece.length,data.length);                                
        return ret;
    }
}
